package pers.muci.moudles.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: LoginFilter
 * Description: 登陆形式 json or key/value
 * date: 2021/10/9 10:57
 *
 * @author muci
 * @since JDK 1.8
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String POST = "POST";
        if (!POST.equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        if (Arrays.asList(MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_JSON_UTF8_VALUE).contains(request.getContentType())){
            Map<String, String> loginData = new HashMap<>(8);
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            }catch (IOException e){

            }finally {

            }
            String username = loginData.get(getUsernameParameter()).trim();
            String password = loginData.get(getPasswordParameter()).trim();
            username = (username != null) ? username : "";
            password = (password != null) ? password : "";
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }else {
            return super.attemptAuthentication(request, response);
        }

    }
}
